package com.ssm.dao;

import com.ssm.domain.Permission;
import com.ssm.domain.Role;
import com.ssm.domain.UserInfo;
import org.apache.ibatis.annotations.*;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface IRoleDao {

    @Select("select * from role where id in (select roleId from users_role where userId = #{userId})")
    List<Role> findById(String userId) throws Exception;


    @Select("select * from role where id in (select roleId from users_role where userId=#{userId})")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "roleName", column = "roleName"),
            @Result(property = "roleDesc", column = "roleDesc"),
            @Result(property = "permissions", column = "id", javaType = java.util.List.class, many = @Many(select = "com.ssm.dao.IPermissionDao.findPermissionByRoleId"))
    })
    List<Role> findRoleByUserId(String userId) throws Exception;

    @Insert("insert into role values(#{id},#{roleName},#{roleDesc})")
    void save(Role role) throws Exception;

    @Select("select * from role")
    List<Role> findAll()throws Exception;

    @Select("select * from role where id not in (select roleId from users_role where userId=#{userId})")
    List<Role> findOtherRoles(String userId)throws Exception;

    @Insert("insert into users_role values(#{userId}, #{roleId})")
    @Transactional
    void addUserToRole(@Param("userId") String userId, @Param("roleId") String roleId);

    @Select("select * from role where id = #{roleId}")
    Role findByRoleId(String roleId);

    @Select("select * from role where id not in (select roleId from role_permission where permissionId=#{permissionId})")
    List<Role> findOtherRolesByPermissionId(String permissionId);

    @Delete("delete a,b,c from role a left join users_role b on a.id = b.userId left join role_permission c on b.roleId = c.roleId where a.id = #{id}")
    void deleteById(String id);

    @Select("select id,email,username,password,phoneNum,status from users where id in (select userId from users_role where roleId = #{id})")
    List<UserInfo> findUserById(String id);
    @Select("select id,permissionName,url from permission where id in (select permissionId from role_permission where roleId = #{id})")
    List<Permission> findPermissionById(String id);
}
